from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
from fastapi.openapi.utils import get_openapi
from app.api.v1.api import api_router
from app.core.config import settings
from app.core.logging_config import get_logger
from app.db.init_db import init_db

# 获取日志记录器
logger = get_logger(__name__)

# 初始化数据库
init_db()

app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    # 禁用默认的文档路由
    docs_url=None,
    redoc_url=None,
    openapi_url=None  # 禁用默认的 openapi.json
)

# CORS配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=settings.ALLOW_CREDENTIALS,
    allow_methods=settings.CORS_METHODS,
    allow_headers=settings.CORS_HEADERS,
)

# 添加路由前缀
app.include_router(api_router, prefix=settings.API_V1_STR)

# 自定义 OpenAPI 文档
def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    
    openapi_schema = get_openapi(
        title=settings.PROJECT_NAME,
        version=settings.VERSION,
        description="Wallet API Documentation",
        routes=app.routes,
    )
    app.openapi_schema = openapi_schema
    return app.openapi_schema

# 文档路由
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url="/openapi.json",
        title=f"{settings.PROJECT_NAME} - Swagger UI",
        swagger_js_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js",
        swagger_css_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css",
    )

@app.get("/redoc", include_in_schema=False)
async def redoc_html():
    return get_redoc_html(
        openapi_url="/openapi.json",
        title=f"{settings.PROJECT_NAME} - ReDoc",
        redoc_js_url="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js",
    )

@app.get("/openapi.json", include_in_schema=False)
async def get_openapi_json():
    return custom_openapi()

@app.middleware("http")
async def log_requests(request: Request, call_next):
    """记录请求和响应"""
    try:
        response = await call_next(request)
        if response.status_code >= 400:
            # 只记录错误响应
            logger.error(
                "Request failed: {} {} - Status: {}",
                request.method,
                request.url,
                response.status_code
            )
        return response
    except Exception as e:
        # 记录未捕获的异常
        logger.exception(
            "Unhandled exception: {} {} - Error: {}",
            request.method,
            request.url,
            str(e)
        )
        raise

@app.on_event("startup")
async def startup_event():
    """应用启动时的处理"""
    logger.info("Application startup")

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时的处理"""
    logger.info("Application shutdown")

if __name__ == "__main__":
    import uvicorn
    logger.info("Starting server...")
    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",  # 监听所有网络接口
        port=8001,
        reload=True,     # 开发模式下启用热重载
        log_level="info"
    ) 